<template>
  <div class="container">
    <MainNav
        :all-categories="allCategories"
        @filter-change="handleFilterChange"
        @login-success="handleLoginSuccess"
        @logout="handleLogout"
    />

    <main class="main-content">
      <header class="header">
        <h1 class="site-title">个人中心</h1>
      </header>
      <div v-if="!isLoggedIn" class="not-logged-in">
        <div class="login-prompt-card">
          <div class="login-icon-container">
            <Icon name="material-symbols:account-circle" class="login-icon" />
          </div>
          <h2 class="login-title">请先登录</h2>
          <p class="login-message">登录后即可查看您的个人信息和定制内容</p>
          <button class="login-button" @click="openLoginModal">
            立即登录
          </button>
        </div>
      </div>
      <div v-else class="profile-container">
        <div class="profile-card">
          <div class="profile-header">
            <img :src="userInfo.avatar" :alt="`${userInfo.name}的头像`" class="profile-avatar">
            <div class="profile-info">
              <h2 class="profile-name">{{ userInfo.name }}</h2>
              <p class="profile-email">{{ userInfo.email }}</p>
              <button class="edit-profile-btn" @click="toggleEditMode">
                <Icon name="material-symbols:edit" class="edit-icon" />
                编辑个人资料
              </button>
            </div>
          </div>
          <div v-if="editMode" class="profile-form">
            <div class="form-group">
              <label class="form-label">姓名</label>
              <input
                  type="text"
                  v-model="editUserInfo.name"
                  class="form-input"
                  placeholder="请输入您的姓名"
              >
            </div>
            <div class="form-group">
              <label class="form-label">邮箱</label>
              <input
                  type="email"
                  v-model="editUserInfo.email"
                  class="form-input"
                  placeholder="请输入您的邮箱"
              >
            </div>
            <div class="form-actions">
              <button class="cancel-btn" @click="toggleEditMode">取消</button>
              <button class="save-btn" @click="saveProfile">保存修改</button>
            </div>
          </div>
        </div>
        <div class="preferences-card">
          <h2 class="card-title">
            <Icon name="material-symbols:settings" class="card-icon" />
            内容偏好
          </h2>
          <div class="preferences-content">
            <p class="preference-desc">选择您感兴趣的金融新闻类别，我们将为您优先展示</p>
            <div class="category-preferences">
              <div
                  v-for="category in allCategories"
                  :key="category"
                  class="category-checkbox"
                  @click="toggleCategoryPreference(category)"
              >
                <div class="checkbox-icon" :class="{ 'checked': isCategoryPreferred(category) }">
                  <Icon name="material-symbols:check" class="check-icon" v-if="isCategoryPreferred(category)" />
                </div>
                <span class="category-name">{{ category }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="history-card">
          <h2 class="card-title">
            <Icon name="material-symbols:history" class="card-icon" />
            浏览历史
          </h2>
          <div v-if="browsingHistory.length > 0" class="history-list">
            <div
                v-for="item in browsingHistory"
                :key="item.id"
                class="history-item"
            >
              <div class="history-info">
                <h3 class="history-title">{{ item.title }}</h3>
                <div class="history-meta">
                  <span class="history-category">{{ item.category }}</span>
                  <time class="history-time">{{ formatTime(item.timestamp) }}</time>
                </div>
              </div>
              <button class="delete-history" @click="deleteHistoryItem(item.id)" aria-label="删除此历史记录">
                <Icon name="material-symbols:delete" class="delete-icon" />
              </button>
            </div>
          </div>
          <div v-else class="no-history">
            <Icon name="material-symbols:history-off" class="no-history-icon" />
            <p>暂无浏览历史</p>
          </div>
          <button
              class="clear-history-btn"
              @click="clearAllHistory"
              :disabled="browsingHistory.length === 0"
              :aria-disabled="browsingHistory.length === 0"
          >
            清除所有历史
          </button>
        </div>
      </div>
    </main>

   <footer class="footer">
     <MainFooter />
   </footer>

    <LoginModal
        :visible="loginModalVisible"
        @close="closeLoginModal"
        @success="handleLoginSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import newsData from '../../../public/data/news.json';
import LoginModal from '@/components/LoginModal/LoginModal.vue';
import MainNav from '@/components/MainNav/MainNav.vue';
import MainFooter from '@/components/Footer/MainFooter.vue';
// 定义类型
interface User {
  id: string;
  name: string;
  email: string;
  avatar: string;
}

interface NewsItem {
  id: string;
  title: string;
  category: string;
  timestamp: string;
}

interface BrowsingHistoryItem extends NewsItem {
  viewTime: string;
}

// 登录状态管理
const loginModalVisible = ref<boolean>(false);
const isLoggedIn = ref<boolean>(false);
const userInfo = ref<User>({
  id: '',
  name: '',
  email: '',
  avatar: ''
});
const editUserInfo = ref<User>({...userInfo.value});
const editMode = ref<boolean>(false);

// 内容偏好设置
const preferredCategories = ref<string[]>([]);

// 浏览历史
const browsingHistory = ref<BrowsingHistoryItem[]>([]);

// 获取所有新闻分类
const allCategories = computed<string[]>(() => [
  ...new Set(newsData.map((item: any) => item.category))
])

// SEO优化：配置页面元数据
useHead({
  title: '个人中心 - 深度关联',
  meta: [
    {
      name: 'description',
      content: '管理您的深度关联账户信息、内容偏好和浏览历史，个性化定制您的金融新闻阅读体验。'
    },
    {
      name: 'keywords',
      content: '个人中心, 账户管理, 内容偏好设置, 浏览历史, 金融新闻定制, 深度关联'
    },
    {
      name: 'viewport',
      content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'
    },
    { name: 'robots', content: 'index, follow' }
  ],
  link: [
    { rel: 'canonical', href: '/profile' } // 规范URL，避免重复内容
  ],
  // 添加结构化数据 - 个人资料页面
  script: [
    {
      type: 'application/ld+json',
      innerHTML: computed(() => JSON.stringify({
        "@context": "https://schema.org",
        "@type": "ProfilePage",
        "name": "用户个人中心 - 深度关联",
        "description": "管理用户账户信息和偏好设置的页面",
        "publisher": {
          "@type": "Organization",
          "name": "深度关联",
          "logo": {
            "@type": "ImageObject",
            "url": "/logo.png" // 替换为实际logo路径
          }
        },
        "mainEntity": isLoggedIn.value ? {
          "@type": "Person",
          "name": userInfo.value.name,
          "email": userInfo.value.email
        } : undefined
      }))
    }
  ]
});

onMounted(() => {
  // 检查本地存储中的登录状态
  const savedUser = localStorage.getItem('userInfo');
  if (savedUser) {
    try {
      const user = JSON.parse(savedUser);
      userInfo.value = user;
      editUserInfo.value = {...user};
      isLoggedIn.value = true;

      // 加载用户偏好设置
      loadUserPreferences();
      // 加载浏览历史
      loadBrowsingHistory();
    } catch (e) {
      console.error('Failed to parse saved user info', e);
    }
  }
})

// 加载用户偏好设置
const loadUserPreferences = () => {
  const prefs = localStorage.getItem(`user_${userInfo.value.id}_preferences`);
  if (prefs) {
    try {
      const preferences = JSON.parse(prefs);
      preferredCategories.value = preferences.categories || [];
    } catch (e) {
      console.error('Failed to parse user preferences', e);
    }
  }
}

// 保存用户偏好设置
const saveUserPreferences = () => {
  if (!userInfo.value.id) return;

  const preferences = {
    categories: preferredCategories.value
  };

  localStorage.setItem(
      `user_${userInfo.value.id}_preferences`,
      JSON.stringify(preferences)
  );
}

// 加载浏览历史
const loadBrowsingHistory = () => {
  const history = localStorage.getItem(`user_${userInfo.value.id}_history`);
  if (history) {
    try {
      browsingHistory.value = JSON.parse(history);
    } catch (e) {
      console.error('Failed to parse browsing history', e);
    }
  }
}

// 保存浏览历史
const saveBrowsingHistory = () => {
  if (!userInfo.value.id) return;

  localStorage.setItem(
      `user_${userInfo.value.id}_history`,
      JSON.stringify(browsingHistory.value)
  );
}

// 登录相关方法
const openLoginModal = () => {
  loginModalVisible.value = true;
};

const closeLoginModal = () => {
  loginModalVisible.value = false;
};

const handleLoginSuccess = (user: User) => {
  isLoggedIn.value = true;
  userInfo.value = user;
  editUserInfo.value = {...user};
  loginModalVisible.value = false;

  // 保存用户信息到本地存储
  localStorage.setItem('userInfo', JSON.stringify(user));

  // 加载用户偏好和历史
  loadUserPreferences();
  loadBrowsingHistory();
};

const handleLogout = () => {
  isLoggedIn.value = false;
  userInfo.value = {
    id: '',
    name: '',
    email: '',
    avatar: ''
  };
  editUserInfo.value = {...userInfo.value};
  preferredCategories.value = [];
  browsingHistory.value = [];

  // 清除本地存储中的用户信息
  localStorage.removeItem('userInfo');
};

// 处理导航栏筛选变化（虽然个人中心可能不需要，但保持接口一致性）
const handleFilterChange = (filters: { category: string; date: string }) => {
  // 可以留空或根据需要实现
  console.log('筛选条件变化:', filters);
};

// 个人资料编辑
const toggleEditMode = () => {
  editMode.value = !editMode.value;
  // 如果退出编辑模式，恢复原始值
  if (!editMode.value) {
    editUserInfo.value = {...userInfo.value};
  }
};

const saveProfile = () => {
  userInfo.value = {...editUserInfo.value};
  localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
  editMode.value = false;

  // 显示保存成功提示
  alert('个人资料已更新');
};

// 内容偏好管理
const isCategoryPreferred = (category: string) => {
  return preferredCategories.value.includes(category);
};

const toggleCategoryPreference = (category: string) => {
  const index = preferredCategories.value.indexOf(category);
  if (index > -1) {
    preferredCategories.value.splice(index, 1);
  } else {
    preferredCategories.value.push(category);
  }
  saveUserPreferences();
};

// 浏览历史管理
const deleteHistoryItem = (id: string) => {
  browsingHistory.value = browsingHistory.value.filter(item => item.id !== id);
  saveBrowsingHistory();
};

const clearAllHistory = () => {
  if (confirm('确定要清除所有浏览历史吗？')) {
    browsingHistory.value = [];
    saveBrowsingHistory();
  }
};

// 格式化时间显示
const formatTime = (timestamp: string): string => {
  const date = new Date(timestamp);
  const now = new Date();

  // 计算时间差（毫秒）
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / (1000 * 60));
  const diffHours = Math.floor(diffMins / 60);
  const diffDays = Math.floor(diffHours / 24);

  // 今天的消息
  if (diffDays === 0) {
    if (diffHours === 0) {
      return `${diffMins}分钟前`;
    } else {
      return `${diffHours}小时前`;
    }
  }
  // 昨天的消息
  else if (diffDays === 1) {
    return `昨天 ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
  }
  // 本周的消息
  else if (diffDays < 7) {
    return `${diffDays}天前`;
  }
  // 更早的消息
  else {
    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
  }
};
</script>

<style scoped>
/* 复用首页的基础样式 */
* {
  -webkit-tap-highlight-color: transparent;
  -webkit-touch-callout: none;
  font-family: "Helvetica Neue", Arial, "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 15px;
  line-height: 1.6;
  color: #333;
  background-color: #f9f9f9;
  min-height: 100vh;
}

/* 主内容区域样式 */
.main-content {
  margin-bottom: 30px;
}

/* 页面标题 */
.header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.site-title {
  font-size: 2.2rem;
  margin: 0 0 8px 0;
  color: #222;
  position: relative;
  display: inline-block;
  font-weight: 700;
}

.site-title::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 10%;
  width: 80%;
  height: 3px;
  background: linear-gradient(90deg, transparent, #3498db, transparent);
  border-radius: 3px;
}

/* 未登录状态样式 */
.not-logged-in {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 50vh;
  padding: 20px;
}

.login-prompt-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0,0,0,0.08);
  padding: 40px 30px;
  text-align: center;
  max-width: 400px;
  width: 100%;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.login-prompt-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0,0,0,0.12);
}

.login-icon-container {
  width: 80px;
  height: 80px;
  background-color: #f1f5f9;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto 20px;
}

.login-icon {
  font-size: 2.5rem;
  color: #3498db;
}

.login-title {
  font-size: 1.5rem;
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-weight: 600;
}

.login-message {
  color: #666;
  margin: 0 0 25px 0;
  font-size: 0.95rem;
  line-height: 1.6;
}

.login-button {
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 30px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(41, 128, 185, 0.2);
  width: 100%;
}

.login-button:hover {
  background: linear-gradient(135deg, #2980b9 0%, #1f6dad 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(41, 128, 185, 0.3);
}

/* 已登录状态 - 个人中心容器 */
.profile-container {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

/* 个人信息卡片 */
.profile-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 3px 15px rgba(0,0,0,0.05);
  padding: 25px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.profile-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 20px rgba(0,0,0,0.08);
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.profile-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f1f5f9;
  box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.profile-info {
  flex: 1;
}

.profile-name {
  font-size: 1.8rem;
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-weight: 600;
}

.profile-email {
  color: #666;
  margin: 0 0 15px 0;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.profile-email::before {
  content: '';
  display: inline-block;
  width: 1px;
  height: 1rem;
  background-color: #ddd;
}

.edit-profile-btn {
  background-color: #f1f5f9;
  color: #3498db;
  border: none;
  border-radius: 6px;
  padding: 8px 15px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.edit-profile-btn:hover {
  background-color: #e1e8ed;
  color: #2980b9;
  transform: translateY(-2px);
}

.edit-icon {
  font-size: 1rem;
}

/* 个人资料表单 */
.profile-form {
  margin-top: 20px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #2c3e50;
  font-size: 0.95rem;
}

.form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  color: #333;
  background-color: #fafafa;
}

.form-input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
  background-color: white;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 10px 20px;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background-color: #eee;
  color: #333;
}

.save-btn {
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
  color: white;
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(41, 128, 185, 0.2);
}

.save-btn:hover {
  background: linear-gradient(135deg, #2980b9 0%, #1f6dad 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(41, 128, 185, 0.3);
}

/* 内容偏好设置卡片 */
.preferences-card, .history-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 3px 15px rgba(0,0,0,0.05);
  padding: 25px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.preferences-card:hover, .history-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 20px rgba(0,0,0,0.08);
}

.card-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 1.3rem;
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-weight: 600;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.card-icon {
  color: #3498db;
  font-size: 1.5rem;
}

.preference-desc {
  color: #666;
  margin: 0 0 20px 0;
  font-size: 0.95rem;
  line-height: 1.6;
}

.category-preferences {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 15px;
}

.category-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 10px 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.95rem;
  border: 1px solid transparent;
}

.category-checkbox:hover {
  background-color: #ebf5fb;
  transform: translateY(-2px);
  border-color: #d6eaf8;
}

.checkbox-icon {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 2px solid #bdc3c7;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.checkbox-icon.checked {
  background-color: #3498db;
  border-color: #3498db;
}

.check-icon {
  color: white;
  font-size: 0.8rem;
}

.category-name {
  color: #333;
  font-weight: 500;
}

/* 浏览历史 */
.history-list {
  margin-top: 15px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  background-color: #fafafa;
  margin-bottom: 12px;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
}

.history-item:hover {
  background-color: #f1f5f9;
  transform: translateX(3px);
  border-left-color: #3498db;
}

.history-info {
  flex: 1;
  min-width: 0;
}

.history-title {
  margin: 0 0 5px 0;
  font-size: 1rem;
  color: #2c3e50;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 0.8rem;
  color: #777;
}

.history-category {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: 500;
  font-size: 0.75rem;
  background-color: #e1e8ed;
  color: #666;
}

.delete-history {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 5px;
  transition: all 0.3s ease;
  opacity: 0;
}

.history-item:hover .delete-history {
  opacity: 1;
}

.delete-history:hover {
  color: #e74c3c;
}

.delete-icon {
  font-size: 1rem;
}

.no-history {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px dashed #eee;
}

.no-history-icon {
  font-size: 2rem;
  margin-bottom: 15px;
  color: #ccc;
}

.clear-history-btn {
  background-color: #fef7f7;
  color: #e74c3c;
  border: 1px solid #fdeaea;
  border-radius: 6px;
  padding: 8px 15px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 20px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.clear-history-btn:hover:not(:disabled) {
  background-color: #fdeaea;
  color: #c0392b;
  transform: translateY(-2px);
}

.clear-history-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.footer {
  text-align: center;
  margin-top: 40px;
  padding: 25px 15px 15px;
  border-top: 1px solid #eee;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .container {
    padding: 10px;
  }

  .site-title {
    font-size: 1.8rem;
  }

  .profile-header {
    flex-direction: column;
    text-align: center;
    padding-bottom: 15px;
  }

  .profile-avatar {
    width: 80px;
    height: 80px;
  }

  .profile-name {
    font-size: 1.5rem;
  }

  .profile-email {
    justify-content: center;
  }

  .form-actions {
    flex-direction: column;
  }

  .cancel-btn, .save-btn {
    width: 100%;
  }

  .category-preferences {
    gap: 10px;
  }

  .category-checkbox {
    padding: 8px 12px;
    font-size: 0.9rem;
    flex: 1;
    min-width: calc(50% - 10px);
    box-sizing: border-box;
  }

  .history-title {
    font-size: 0.9rem;
  }
}

/* 针对小屏手机的额外适配 */
@media (max-width: 480px) {
  .category-checkbox {
    min-width: 100%;
  }

  .profile-card, .preferences-card, .history-card {
    padding: 15px;
  }
}
</style>